<template>
  <div id="app" class="product-sample-cut">
    <van-nav-bar left-arrow title="成品剪样" @click-left="comeBack" left-text="返回">
      <template #right>
        <van-button size="mini" type="warning" @click="openScanWin4ReturnedFn" style="margin-right: 3vw">退货</van-button>
        <span @click="showAddDialog = true"><van-icon name="plus" size="20" /></span>
      </template>
    </van-nav-bar>
    <!-- 筛选 -->
    <van-search v-model="queryParam.keyLike" placeholder="请输入搜索关键词" @search="loadSampleCutDataFn(1)" />

    <!-- 滚动 -->
    <better-scroll class="public-scroll" :data="sampleCutData" :total-page="totalPage" :pulldown="true" :pullup="true" @pullup="loadNextPageFn" @pulldown="loadSampleCutDataFn(1)">
      <van-swipe-cell v-for="row in sampleCutData" :key="row.id" style="padding-bottom: 0.5rem">
        <template>
          <div class="data-card">
            <div style="border-bottom: 1px solid #8191c5; font-size: 1.2rem;color: #1677FF;justify-content: space-between">
              <span>{{ row.customer }}</span>
            </div>
            <div style="justify-content: space-between">
              <span style="color: #e6a23c">品名: {{ row.designNo }}</span>
            </div>
            <div style="justify-content: space-between">
              <span style="color: #e6a23c">匹号: {{ row.designSeqNo }}</span>
              <span style="color: #e6a23c">米数: {{ row.length }}(实:{{ row.actualLength }}) 米</span>
              <span style="color: #e6a23c">来源: {{ row.fromType == 1 ? "成品" : row.fromType == 2 ? "旧布" : row.fromType == 3 ? "坯布" : row.fromType == 4 ? "外购" : row.fromType == 5 ? "坯布试样" : row.fromType == 7 ? "退货剪样" : SPLIT_BLANK }}</span>
            </div>
            <div style="justify-content: space-between;font-size: 1rem; border-top: 1px solid #8191c5">
              <span>{{ row.cutterName }}</span>
              <span>{{ row.cutAt }}</span>
            </div>
          </div>
        </template>
        <template #right>
          <div style="display: flex; flex-direction: column; justify-content: space-between;height: 100%;">
            <div><van-button square text="删除" size="small" type="danger" @click="delSampleDataFn(row)" /></div>
            <div><van-button square text="打印" size="small" type="primary" @click="printFn(row)"></van-button></div>
            <div><van-button square text="退货" size="small" type="warning" @click="showReturnedFn(row)"></van-button></div>
          </div>
        </template>
      </van-swipe-cell>
    </better-scroll>

    <!-- 开始扫码弹窗 -->
    <van-dialog v-model="showAddDialog" title="新增剪样" show-cancel-button @confirm="openScanWinFn">
      <div style="width: 75vw;">
        <van-field label="客户" label-align="right" size="large" label-width="20vw" colon placeholder="请选择客户" v-model="addParam.customer" readonly @click="showCustomerPickerFn('customer')">
        </van-field>
        <van-field label="需要长度" label-align="right" size="large" label-width="20vw" clearable colon placeholder="请输入米数" v-model="addParam.length" @change="() => addParam.actualLength = addParam.length">
          <template #extra>米</template>
        </van-field>
        <van-field label="实剪长度" label-align="right" size="large" label-width="20vw" clearable colon placeholder="请输入米数" v-model="addParam.actualLength">
          <template #extra>米</template>
        </van-field>
        <van-radio-group style="margin-left: 15vw; margin-top: 1vh;margin-bottom: 1vh" v-model="addParam.fromType" direction="horizontal">
          <van-radio shape="square" name="1">扫码</van-radio>
          <van-radio shape="square" name="4">外购</van-radio>
        </van-radio-group>
        <van-field v-if="addParam.fromType == 4" label="品名" label-align="right" size="large" label-width="20vw" colon placeholder="请输入品名" v-model="addParam.designNo"></van-field>
        <van-field v-if="addParam.fromType == 4" label="颜色" label-align="right" size="large" label-width="20vw" colon placeholder="请输入品名" v-model="addParam.color"></van-field>
        <van-field v-if="addParam.fromType == 4" label="来源" label-align="right" size="large" label-width="20vw" colon placeholder="请选择供应商" v-model="addParam.supplier" readonly @click="showCustomerPickerFn('supplier')">
        </van-field>
      </div>
    </van-dialog>

    <!-- 客户选项弹窗 -->
    <van-action-sheet v-model="customerPicker.show" :actions="customerPicker.data" close-on-click-action @select="selectCustomerFn" get-container="body">
      <template slot="description">
        <van-search v-model="customerPicker.name" type="text" placeholder="输入名称" clearable @search="loadCustomerDataFn"></van-search>
      </template>
    </van-action-sheet>

    <!-- 坯布分段样品 -->
    <van-popup v-model="greyCloth.show" get-container="#app">
      <div v-if="greyCloth.data.id > 0" class="data-card">
        <div style="flex: 1; flex-flow: column;">
          <div style="border-bottom: 1px solid #08b70a; display: flex;justify-content: space-between" >
            <span style="color: #08b70a;font-size: 1rem; ">{{ greyCloth.data.designNo }}</span>
            <van-checkbox shape="square" style="margin-top: -1vh;" v-model="greyCloth.selected" @click="() => selectGreyClothSampleFn()"></van-checkbox>
          </div>
          <div style="display:flex; justify-content: space-between;">
            <span style="color: #bb5a09;font-size: 1rem; ">{{ greyCloth.data.colorNo }}</span>
            <span style="color: #bb5a09;font-size: 1rem; ">匹号:{{ greyCloth.data.designSeqNo }}</span>
            <span style="color: #bb5a09;font-size: 1rem; ">{{ greyCloth.data.length }}米</span>
          </div>
        </div>
      </div>
      <grey-cloth-sample style="margin-top: 2vh;max-height: 70vh;overflow: auto" v-if="greyCloth.show" :grey-cloth-id="greyCloth.data.id" :show-yarn="false" :select="true" @selected="selectGreyClothSampleFn" @close="greyCloth.show = false"></grey-cloth-sample>
    </van-popup>

    <!-- 盘库剪样确认框 -->
    <van-dialog v-model="checkCut.show" title="请确认出库匹数" width="60vw" show-cancel-button @cancel="addParam.checkId = 0" @confirm="confirmCutByStoreCheckFn">
      <van-field type="digit" label="出库匹数" clearable v-model="checkCut.outNum"></van-field>
    </van-dialog>

    <!-- 客户退货 -->
    <van-dialog v-model="returned.show" title="请确认退货米数" width="60vw" show-cancel-button @cancel="returned.sampleCut.id = 0" @confirm="customerReturnedFn">
      <van-field type="number" label="实际米数" clearable v-model="returned.sampleCut.actualLength"></van-field>
    </van-dialog>
  </div>
</template>

<script>
import {comeBack} from "@/utils";
import {
  addProductSampleCut, addProductSampleCutByGreyCloth, addProductSampleCutByOutsource, addProductSampleCutBySampleCut,
  addProductSampleCutByStoreCheck, customerReturnSampleCut,
  delSampleData,
  getCustomerInfoList,
  loadSampleCutData, queryProductSampleCutDetail
} from "@/api/product";
import {SPLIT_BLANK} from "@/api/enum";
import {loadGreyClothSampleData, queryGreyClothDetail} from "@/views/weaving/weaving";
import GreyClothSample from "@/views/weaving/grey-cloth-sample/App";
import {BluetoothPrint} from "@/utils/btlPrint";
import dayjs from "dayjs";


export default {
  name: "productSampleCut",
  components: {GreyClothSample},
  data() {
    return {
      SPLIT_BLANK,

      /* 查询条件 */
      queryParam: {
        keyLike: SPLIT_BLANK,
        pageNum: 1,
        pageSize: 7,
      },

      /* 列表相关 */
      sampleCutData: [],
      totalPage: 0,

      /* 操作相关 */
      showAddDialog: false,
      addParam: {
        customerId: 0,
        customer: SPLIT_BLANK,
        length: SPLIT_BLANK,
        actualLength: SPLIT_BLANK,
        detailId: SPLIT_BLANK,
        detailFlag: SPLIT_BLANK,
        fromType: "1",
        supplierId: 0,
        supplier: SPLIT_BLANK,
        greyClothId: 0,
        greyClothSampleId: 0,
        designNo: SPLIT_BLANK,
        color: SPLIT_BLANK,
        upperId: 0,
      },
      /* 客户相关 */
      customerPicker: {
        show: false,
        field: SPLIT_BLANK,
        data: [],
        name: SPLIT_BLANK,
      },

      /* 坯布分段样品 */
      greyCloth: {
        show: false,
        data: {
          id: 0,
          designNo: SPLIT_BLANK,
          colorNo: SPLIT_BLANK,
          designSeqNo: 0,
          length: 0
        },
        selected: false,
      },

      /* 打印实例 */
      printObj: null,

      /* 盘库剪样 */
      checkCut: {
        show: false,
        outNum: 0,
      },

      /* 客户退货 */
      returned: {
        show: false,
        sampleCut: {
          id: 0,
          actualLength: 0
        },
      }
    };
  },
  mounted() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      that.$nextTick(() => {
        that.initFn();
      });
    } else {
      window.apiready = function () {
        that.initFn();
      };
    }

    // that.initFn(that);   //dev fixme
  },
  methods: {
    comeBack,

    //初始化
    initFn() {
      const that = this;
      that.loadSampleCutDataFn(1);
      that.printObj = new BluetoothPrint(that, that.printCallbackFn);
    },

    // 获取客户列表
    loadCustomerDataFn() {
      let that = this;
      that.customerPicker.data.splice(0, that.customerPicker.data.length);
      getCustomerInfoList({
        name: that.customerPicker.name,
      }, (res) => {
        if (res.list.length) {
          res.list.forEach((item) => {
            that.customerPicker.data.push({
              id: item.id,
              name: item.company + "_" + item.name,
            });
          });
        }
      });
    },

    /* 显示客户选择 */
    showCustomerPickerFn(field) {
      const that = this;
      that.customerPicker.field = field;
      that.customerPicker.show = true
    },

    // 确认客户供应商
    selectCustomerFn(item) {
      const that = this;
      that.addParam[that.customerPicker.field + "Id"] = item.id;
      that.addParam[that.customerPicker.field] = item.name;
      that.customerPicker.show = false;
    },

    //打开扫码窗口
    openScanWinFn() {
      const that = this;
      if("4" == that.addParam.fromType) {
        addProductSampleCutByOutsource(that.addParam, row => that.addProductSampleCutSubFn(that, row));
      } else {
        that.addParam.detailId = 0;
        that.addParam.detailFlag = 0;
        that.addParam.checkId = 0;
        if(that.addParam.length <= 0) {
          that.$toast.fail("米数必须");
          return;
        }
        const zyHmsScan = api.require('zyHmsScan');
        zyHmsScan.openDefaultView({}, ret => {
          if(ret.status) {
            let content = ret.result;
            if(content.indexOf("15,") === 0) {    //扫盘库码
              that.addParam.checkId = content.substring(3, content.length);
              that.checkCut.show = true;
            } else if(content.indexOf("http://") == 0) {    //扫成品码
              content = content.substring(content.lastIndexOf("/")+1, content.length);
              let contents = content.split("?");
              that.addParam.detailId = contents[0];
              if(contents[1]) {
                that.addParam.detailFlag = 1;
              }
              addProductSampleCut(that.addParam, row => that.addProductSampleCutSubFn(that, row));
            } else if(content.indexOf("37,") == 0) {
              that.addParam.upperId = content.substring(3, content.length);
              addProductSampleCutBySampleCut(that.addParam, row => that.addProductSampleCutSubFn(that, row));
            } else {
              that.greyCloth.data.id = Number(content);
              if(that.greyCloth.data.id) {
                queryGreyClothDetail(that.greyCloth.data.id, data => {
                  Object.keys(that.greyCloth.data).forEach(key => {
                    that.greyCloth.data[key] = data[key];
                  });
                  that.greyCloth.show = true;
                });
              } else {
                that.$toast.fail("请扫坯布码");
              }
            }
          }
        });
      }
    },
    addProductSampleCutSubFn(that, row) {
      that.printFn(row);
      that.sampleCutData.splice(0, 0, row);
      if(that.addParam.fromType != "4") {   //重置为扫码
        that.addParam.fromType = "1";
        that.greyCloth.show = false;
      }
      that.$toast.success({
        type: "success",
        message: "剪样成功,请继续",
        onClose: function () {
          if("4" != that.addParam.fromType) {
            that.openScanWinFn();
          }
        },
        duration: 1500
      });
    },


    //加载剪样数据
    loadSampleCutDataFn(pageNum) {
      let that = this;
      if(pageNum == 1) {
        that.sampleCutData.splice(0, that.sampleCutData.length);
        that.queryParam.pageNum = pageNum;
      }
      loadSampleCutData(that.queryParam, data => {
        that.totalPage = data.totalPage;
        data.list.forEach(row => {
          that.sampleCutData.push(row);
        });
      });
    },

    //加载下一页
    loadNextPageFn() {
      let that = this;
      that.queryParam.pageNum++;
      that.loadSampleCutDataFn();
    },

    //删除剪样数据
    delSampleDataFn(row) {
      const that = this;
      that.$dialog.confirm({
        title: "请确认",
        message: "将删除这块剪样?",
        confirmButtonText: "删除"
      }).then(() => {
        delSampleData({cutId: row.id}, () => {
          that.$toast.success("删除成功");
          that.sampleCutData.splice(that.sampleCutData.findIndex(data => data.id == row.id), 1);
        });
      }).catch(() => {});
    },

    /* 选择坯布样品 */
    selectGreyClothSampleFn(sampleData, curRow) {
      const that = this;
      if(sampleData) {
        sampleData.filter(sample => sample != curRow).forEach(sample => {
          sample.selected = false;
        });
        curRow.selected = true;
      }
      that.$dialog.confirm({
        title: "剪样米数:" + that.addParam.length + " 实剪:" + that.addParam.actualLength,
        message: "请确认花型\n" + (curRow ? curRow.no : that.greyCloth.data.designNo),
        messageAlign: "center"
      }).then(() => {
        that.$toast.loading({
          message: "操作中...",
          forbidClick: true,
          duration: 0
        });
        that.addParam.fromType = "3";
        that.addParam.greyClothId = that.greyCloth.data.id;
        if(curRow) {
          that.addParam.fromType = "5";
          that.addParam.greyClothSampleId = curRow.id;
        }
        addProductSampleCutByGreyCloth(that.addParam, data => that.addProductSampleCutSubFn(that, data));
      }).catch(() => {});
    },

    /* 打印 */
    printCallbackFn() {
      const that = this;
    },
    printFn(sampleCut) {
      const that = this;
      that.printObj.print([{
        lineType: "size",
        width: 50,
        height: 70,
      }, {
        lineType: "gap",
        data: 3,
      }, {
        lineType: "cls",
      }, {
        // 图片单元格竖线
        lineType: "bar",
        x: 25 + 130,
        y: 0,
        width: 2,
        height: 136,
      }, {
        //绘制图片
        lineType: "image",
        x: 25 + 8,
        y: 8,
        data: "widget://image/huibo_logo.png",
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 10,
        rotation: 0,
        xscal: 1,
        yscal: 1,
        data: "",
      }, {
        // 横线
        lineType: "bar",
        x: 25 + 4,
        y: 186,
        width: 130,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 136 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: dayjs().format("YYYY-MM-DD"),
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 236,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 8,
        y: 236,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "成品剪样码（" + sampleCut.id.toString() + "）",
      }, {
        lineType: "qrcode", // 绘制qrcode
        x: 25 + 150 + 2,
        y: 10,
        level: "L", //L|M|H|Q
        cellwith: 9,
        rotation: 0, // 0|90|180|270
        data: "37," + sampleCut.id.toString(),
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 286 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "品名: " + sampleCut.designNo,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 286,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 336 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "色号: " + sampleCut.color,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 336,
        width: 608,
        height: 2,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 386 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "米数: " + sampleCut.length,
      }, {
        //绘制文本
        lineType: "text",
        x: 25 + 200 + 4,
        y: 386 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "实剪: " + sampleCut.actualLength,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 386,
        width: 608,
        height: 2,
      }, /*{
        //绘制文本
        lineType: "text",
        x: 25 + 4,
        y: 436 + 2,
        rotation: 0,
        xscal: 1,
        yscal: 2,
        data: "操作人: " + sampleCut.cutterName,
      }, */{
        // 横线
        lineType: "bar",
        x: 25,
        y: 436,
        width: 608,
        height: 2,
      }, {
        // 横线
        lineType: "bar",
        x: 25,
        y: 486,
        width: 608,
        height: 2,
      }]);
    },

    /* 确认盘库剪样 */
    confirmCutByStoreCheckFn() {
      const that = this;
      that.addParam.outNum = that.checkCut.outNum;
      addProductSampleCutByStoreCheck(that.addParam, row => that.addProductSampleCutSubFn(that, row));
    },

    /* 客户退货 */
    openScanWin4ReturnedFn() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
          if(ret.status) {
            let content = ret.result;
            if(content.indexOf("37,") == 0) {
              that.sampleCutData.splice(0, that.sampleCutData.length);
              queryProductSampleCutDetail(content.substring(3, content.length), data => {
                that.sampleCutData.push(data);
                that.showReturnedFn(data);
              });
            } else {
              that.$toast.fail("不支持的二维码");
            }
          }
      });
    },
    showReturnedFn(sampleCut) {
      const that = this;
      that.returned.sampleCut.id = sampleCut.id;
      that.returned.sampleCut.actualLength = sampleCut.actualLength;
      that.returned.show = true;
    },
    customerReturnedFn() {
      const that = this;
      that.$dialog.confirm({
        title: "请确认",
        message: "客户退货实际米数:" + that.returned.sampleCut.actualLength,
        confirmButtonText: "确认"
      }).then(() => {
        customerReturnSampleCut({
          sampleCutId: that.returned.sampleCut.id,
          actualLength: that.returned.sampleCut.actualLength,
        }, () => {
          that.loadSampleCutDataFn(1);
        });
      }).catch(() => {});
    }
  }
}
</script>

<style lang="scss" scoped>
.product-sample-cut {
  height: 100%;
  ::v-deep .van-search {
    z-index: 1;
  }
  .public-scroll {
    height: 79vh;
    .van-swipe-cell__right {
      display: flex;
      flex-flow: column;
    }
  }

  .data-card {
    width: 96vw;
    padding: 0.8rem;
    margin-left: 2vw;
    background-color: white;
    margin-top: 0.5rem;
    box-shadow: 0.3rem 0.5rem 0.3rem #888888;
    div {
      display: flex;
      padding: 0.3rem 0rem;
      span {
        line-height: 1rem;
      }
    }
  }
}
</style>